import React, { useState, useEffect } from 'react';
import { SliderContainer } from './style';
import "swiper/dist/css/swiper.css";
import Swiper from 'swiper';

function Slider(props) {
    const [sliderSwiper, setSliderSwiper] = useState(null);
    const { bannerList } = props;

    useEffect(() => {
        if (bannerList.length && !sliderSwiper) {
            // 这部分主要是看 swiper 的API (based on your demand)
            let newSliderSwiper = new Swiper('.slider-container', {   
                loop: true,  // 循环
                effect: 'slide', // 切换效果
                autoplay: {  // 自动播放
                    delay: 3000, 
                    stopOnLastSlide: false,
                    disableOnInteraction: false,
                },
                pagination: {
                    el: '.swiper-pagination',
                },
            });
            setSliderSwiper(newSliderSwiper); 
        };
    }, [ bannerList.length, sliderSwiper]); 
    // useEffect第二个参数是指：对比list里面的元素，有变化就会执行useEffect

    return (
        <SliderContainer>
            <div className="before"></div>
            <div className='slider-container'>
                <div className='swiper-wrapper'>
                    {
                        bannerList.map(slider => {
                            // console.log(slider.targetId)
                            return (
                                <div className='swiper-slide' key={slider.imageUrl}>
                                    <div className='slider-nav'>
                                        <img src={slider.imageUrl} width='100%' height='100%' alt='推荐'></img>
                                    </div>
                                </div>
                            )
                        })
                    }
                </div>
                <div className='swiper-pagination'></div>
            </div>
        </SliderContainer>
    )
};


export default React.memo(Slider);
